package com.github.yeecode.mybatisdemo.xml;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.parsing.*;
import org.w3c.dom.*;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * 模仿mybatis 去解析 properties 节点的数据
 */
public class DemoApplicationCp0 {
    public static void main(String[] args) throws InterruptedException, ParserConfigurationException, IOException, SAXException {



        Properties properties = Resources.getResourceAsProperties("jdbc.properties");
        //定义数据源的xml片段, 当然这个是 spring的, 你也可以改成mybatis 的; 但是道理都是相通的;
        String xml ="<?xml version='1.0' encoding='utf-8'?>"+
                "<bean id='dataSource' class='org.apache.commons.dbcp.BasicDataSource' destroy-method='close' >    " +
                "    <property name='driverClassName' value='${driver}' />" +
                "    <property name='url' value='${url}' />    " +
                "    <property name='username' value='${username}' />    " +
                "    <property name='password' value='${password}' />    " +
                "</bean>";
        //初始化XPathParser
        XPathParser xPathParser = new XPathParser(xml,false,properties);
        //解析表达式，获取XNode对象
        XNode xnode = xPathParser.evalNode("//bean");

        System.out.println("xnode ==> "+ xnode);
        System.out.println(xnode.getValueBasedIdentifier());
        System.out.println(xnode.getStringAttribute("id"));
        System.out.println(xnode.getStringAttribute("class"));

        //下面调用 PropertyParser 和 GenericTokenParser  的函数把对应的值设置进去

        MyPropertyParser.VariableTokenHandler handler = new MyPropertyParser.VariableTokenHandler(properties);
        String s = handler.handleToken(xml);
        System.out.println(s);
        GenericTokenParser parser = new GenericTokenParser("${", "}", handler);
        System.out.println(parser.parse(xml));

    }
}
